package com.changgou.search.controller;


import com.changgou.entity.Page;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private SearchService searchService;

    /**
     * 全文检索
     * @return
     */
    @GetMapping
    @ResponseBody
    public Map search(@RequestParam Map<String,String> searchMap){

        //特殊符号处理
        this.handleSearchMap(searchMap);
        Map searchResult = searchService.search(searchMap);
        return searchResult;
    }

    //对搜索入参带有特殊符号进行处理
    private void handleSearchMap(Map<String, String> searchMap) {

        if(null != searchMap){
            Set<Map.Entry<String, String>> entries = searchMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                if(entry.getKey().startsWith("spec_")){
                    searchMap.put(entry.getKey(),entry.getValue().replace("+","%2B"));
                }
            }
        }
    }


    @GetMapping("/list")
    public String list(@RequestParam Map<String,String> searchMap, Model model){
        //特殊符号处理
        handleSearchMap(searchMap);

        //执行返回值
        Map<String,Object> resultMap = searchService.search(searchMap);

        model.addAttribute("searchMap",searchMap);
        model.addAttribute("result",resultMap);


        //封装分页数据并返回
        Page<SkuInfo> page = new Page<SkuInfo>(
                Long.parseLong(resultMap.get("totalPages").toString()),
                Integer.parseInt(resultMap.get("pageNum").toString()),
                Integer.parseInt(resultMap.get("pageSize").toString())
        );
        model.addAttribute("page",page);


        //拼接url
        StringBuilder url = new StringBuilder("/search/list");
        if(searchMap != null && searchMap.size()>0){
            //查询条件
            url.append("?");
            for (String paramKey : searchMap.keySet()) {
                if(!"sortRule".equals(paramKey)&&!"sortField".equals(paramKey)&&!"pageNum".equals(paramKey)){
                    url.append(paramKey).append("=").append(searchMap.get(paramKey)).append("&");
                }
            }
            //http://localhost:9009/search/list?keywords=手机&spec_网络制式=4G&
            String urlString = url.toString();

            //去除路径上的最后一个&
            urlString = urlString.substring(0,urlString.length()-1);
            model.addAttribute("url",urlString);
        }else {
            model.addAttribute("url",url);
        }

        return "search";
    }


}
